<?php
/**
 * Created by PhpStorm.
 * User: ouryun
 * Date: 2021/5/15
 * Time: 15:36
 */

namespace app\admin\controller;


use Endroid\QrCode\QrCode;
use think\admin\Controller;
use think\admin\extend\DataExtend;

/**
 * 门店管理员管理
 * Class ShopAdmin
 * @package app\admin\controller
 */
class ShopAdmin extends Controller
{
    /**
     * 门店管理员表
     * @var string
     */
    protected $table = 'lg_shop_admin';

    /**
     * 门店管理列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @auth true
     * @login true
     */
    public function index()
    {
        $this->title = '门店管理员列表';
        $data = $this->request->param();
        $query = $this->_query($this->table)->alias('sa')
            ->join('lg_department d', 'sa.department_id=d.id', 'LEFT')
            ->field('sa.*,d.name department_name')
            ->order('sa.id DESC');
        if (isset($data['department_id']) && $data['department_id'] !== '') {
            $query->where('sa.department_id', $data['department_id']);
        }
        if (isset($data['name']) && !empty($data['name'])) {
            $query->whereLike('sa.name', "%{$data['name']}%");
        }
        $query->page();
    }

    /**
     * 处理列表数据
     * @param $list
     * @throws \Endroid\QrCode\Exceptions\ImageFunctionFailedException
     * @throws \Endroid\QrCode\Exceptions\ImageFunctionUnknownException
     * @throws \Endroid\QrCode\Exceptions\ImageTypeInvalidException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function _page_filter(&$list)
    {
        foreach ($list as $key => $value) {
            $shop_id=$value['shop_id'];
            $shop_name="";
            if($shop_id){
                $shop_id=trim(trim($shop_id,' '));
                $shop_id=trim(trim($shop_id,','));
                $shop= $this->app->db->name('lg_distributor')->where("id in($shop_id)")->order("id desc")->column("name");
                if($shop){
                    $shop_name=implode(",",array_values(array_unique($shop)));
                }
            }
            $list[$key]['shop_name'] =$shop_name;
            $list[$key]['qrcode'] = $this->getQrcode($value['id']);
        }
        $department = $this->app->db->name('lg_department')->where('status', 1)->field('id,name,pid')->select()->toArray();
        $department = DataExtend::arr2table($department);
        $this->assign([
            'departmentList' => $department,
        ]);
    }

    /**
     * 添加
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @auth true
     * @login true
     */
    public function add()
    {
        sysoplog('门店管理员管理', '添加数据成功');
        $this->_form($this->table, 'form');
    }

    /**
     * 处理表单数据
     * @param $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function _form_filter(&$data)
    {
        $department = $this->app->db->name('lg_department')->where('status', 1)->field('id,name,pid')->select()->toArray();
        $department = DataExtend::arr2table($department);
        $distributor = $this->app->db->table('lg_distributor')->order('id asc')->field('name,id')->select();
        $this->assign([
            'departmentList' => $department,
            'distributor' => json_encode($distributor,JSON_UNESCAPED_UNICODE)
        ]);
        if ($this->request->isPost()) {
            $post = $this->request->param();
            $valResult = $this->app->validate->check($post, [
                'phone|手机号码' => 'require|mobile'
            ]);
            if ($valResult !== true) {
                $this->error($this->app->validate->getError());
            }
            if (isset($data['id'])) {
                $data['update_time'] = time();
            } else {
                $data['create_time'] = time();
                //todo 加密方式与添加后台用户一样，请勿修改
                $data['password'] = md5('123456');
                $isExist = $this->app->db->name('lg_shop_admin')->where('phone', $data['phone'])->value('id');
                if (!empty($isExist)) {
                    $this->error('该号码已存在');
                }
            }
        }
    }

    /**
     * 修改
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @auth true
     * @login true
     */
    public function edit()
    {
        $id = input('id', '0');
        sysoplog('门店管理员管理', "修改id为{$id}数据成功");
        $this->_form($this->table, 'form');
    }

    /**
     * 删除
     * @throws \think\db\exception\DbException
     * @auth true
     * @login true
     */
    public function remove()
    {
        $id = input('id', '0');
        sysoplog('门店管理员管理', "删除id为{$id}数据成功");
        $this->_delete($this->table);
    }

    /**
     * 清除授权
     * @auth true
     * @login true
     * @throws \think\db\exception\DbException
     */
    public function clearAuth()
    {
        $id = input('id', '0');
        $result = $this->app->db->name($this->table)->where('id', $id)->update(['openid' => '']);
        if ($result) {
            sysoplog('门店管理员管理', session('user.username') . '清除id为' . $id . '门店管理员授权信息');
            $this->success('成功');
        }
        $this->error('失败');
    }

    /**
     * 获取二维码
     * @param $id
     * @return string
     * @throws \Endroid\QrCode\Exceptions\ImageFunctionFailedException
     * @throws \Endroid\QrCode\Exceptions\ImageFunctionUnknownException
     * @throws \Endroid\QrCode\Exceptions\ImageTypeInvalidException
     */
    public function getQrcode($id)
    {
        $qrcode = new QrCode();
        $url = 'http://huawei.9999jt.com/admin/shopAdmin/auth?id=' . $id;
        $qrcode->setText($url)->setSize(300)->setPadding(20);
        $content = base64_encode($qrcode->setImageType('png')->get());
        return 'data:image/png;base64,' . $content;
    }

    /**
     * 微信公众号APPid
     */
    const APP_ID = 'wx421cc73af8168c84';

    /**
     * 微信公众号secret
     */
    const APP_SECRET = '1a6516dad6dc089b352999af495eaf83';

    /**
     * 授权页面
     */
    public function auth()
    {
        $this->fetch();
    }

    /**
     * 获取openid
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function getOpenid()
    {
        $code = input('code', '');
        $id = input('id', '0');
        if (empty($code)) {
            return json(['code' => 400, 'msg' => 'code不能为空']);
        }
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
        $requestUrl = sprintf($url, self::APP_ID, self::APP_SECRET, $code);
        $result = https_request($requestUrl);
        $arr = json_decode($result, true);
        if (isset($arr['openid']) ) {
            $res = $this->app->db->name($this->table)->where('id', $id)->update(['openid' => $arr['openid'], 'update_time' => time()]);
            if ($res) {
                return json(['code' => 200, 'msg' => '绑定成功']);
            }
            return json(['code' => 400, 'msg' => '绑定失败']);
        }
        return json(['code' => 400, 'msg' => '授权失败,请重新扫码']);
    }
}